<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/14
 * Time: 18:55
 */
function load_setting($key = false)
{
    if (!isset($GLOBALS['.setting.php_content'])) {
        $file = Z_DR . '/.setting.php';

        if (is_file($file)) {
            $setting = require $file;
        }
        else {
            $setting = NULL;
        }

        if (!is_array($setting)) {
            $setting = array(
                'smtp'    => array(),
                'payment' => array()
            );
        }

        $GLOBALS['.setting.php_content'] = $setting;
    }

    if (!empty($key)) {
        return $GLOBALS['.setting.php_content'][$key];
    }

    return $GLOBALS['.setting.php_content'];
}

/*支付类型*/
function load_payment_config() {
    $enabled = array ();
    foreach (load_setting('payment') as $single ) {
        if (! $single ['disabled']) {
            $enabled[$single['type']] = $single;
        }
    }

    return $enabled;
}
function _get_payment_config($type) {
    $config = load_payment_config ();
    return $config [$type];
}
function get_paymet_name($type){
    $config = _get_payment_config($type);
    return $config['name'];
}
/*按照支付方式生成html*/
function recharge_by_type($recharge) {
    $notify = 'http://www.qggwsc.net/index.php/Home/PayRecharge/notify/method_code/'.$recharge['method'];
    $return = 'http://www.qggwsc.net/index.php/Home/PayRecharge/ret/method_code/'.$recharge['method'];

    switch ($recharge['method']) {
        case 'ecpay' :
            return ecpay_make_html ( $recharge, $notify, $return );
        case 'allinpay' :
            return allinpay_make_html ( $recharge, $notify, $return );
        case 'ccb' :
            return ccb_make_html ( $recharge, $notify, $return );
        case 'alipay' :
            return alipay_make_html ( $recharge, $notify, $return );
        case 'yeepay' :
            return yeepay_make_html ( $recharge, $notify, $return );
        case 'ryfpaywx' :
            return ryfpaywx_make_html ( $recharge, $notify, $return );
        case 'zzb' :
            return zzb_make_html($recharge, $notify, $return);
    }

    return '';
}

/*按照支付方式生成html*/
function order_by_type($order) {
    $notify = 'http://www.qggwsc.net/index.php/Home/PayOrder/notify/method_code/'.$order['method'];
    $return = 'http://www.qggwsc.net/index.php/Home/PayOrder/ret/method_code/'.$order['method'];

    switch ($order['method']) {
        case 'ecpay' :
            return ecpay_make_html ( $order, $notify, $return );
        case 'allinpay' :
            return allinpay_make_html ( $order, $notify, $return );
        case 'ccb' :
            return ccb_make_html ( $order, $notify, $return );
        case 'alipay' :
            return alipay_make_html ( $order, $notify, $return );
        case 'yeepay' :
            return yeepay_make_html ( $order, $notify, $return );
        case 'ryfpaywx' :
            return ryfpaywx_make_html ( $order, $notify, $return );
        case 'zzb' :
            return zzb_make_html($order, $notify, $return);
    }

    return '';
}

function recharge_callback_by_type($method) {
    switch ($method) {
        case 'ecpay' :
            return ecpay_callback ();
        case 'allinpay' :
            return allinpay_callback ();
        case 'ccb' :
            return ccb_callback ();
        case 'alipay' :
            return alipay_callback ();
        case 'yeepay' :
            return yeepay_callback ();
        case 'ryfpaywx' :
            return ryfpaywx_callback ();
        case 'zzb' :
            return zzb_callback();
    }

    throw new Exception ( '错误的方式: ' . $method . ', ' . $_GET ['method_code'] );
}

/*支付宝支付生成html*/
function alipay_make_html($recharge, $notify, $return) {
    $config = _get_payment_config ( 'alipay' );
    // 构造要请求的参数数组，无需改动
    $parameter = array (
        "service" => 'create_direct_pay_by_user',
        "partner" => $config ['account'] ['partner'],
        "seller_id" => $config ['account'] ['partner'],
        "payment_type" => '1',
        "notify_url" => $notify,
        "return_url" => $return,
        "out_trade_no" => $recharge ['id'],
        "subject" => '支付 ' . $recharge ['amount'],
        "total_fee" => number_format($recharge ['amount'], 2, ".", "" ),
        "body" => '支付 ' . $recharge ['amount'],
        "_input_charset" => 'utf-8'
    );
    // 除去待签名参数数组中的空值和签名参数
    $para_filter = paraFilter ( $parameter );
    // 对待签名参数数组排序
    $para_sort = argSort ( $para_filter );
    $prestr = createLinkstring ( $para_sort );
    // 生成签名结果
    $mysign = md5 ( $prestr . $config ['account'] ['key'] );
    // 签名结果与签名方式加入请求提交参数组中
    $para_sort ['sign'] = $mysign;
    $para_sort ['sign_type'] = strtoupper ( 'MD5' );
    $retStr = "<fieldset> <legend><span style='color: red'>".$config['name']."</span></legend><table style=\"width: 100%\"><tr style=\"vertical-align: top\"><td style=\"padding-left: 20px;padding-right: 20px;\">";
    $retStr .= '<form target="make-payment" style="margin:10px auto" action="https://mapi.alipay.com/gateway.do" method="get">';
    foreach ( $para_sort as $key => $value ) {
        $retStr .= '<input type="hidden" name="' . $key . '" value="' . $value . '" />';
    }
    $retStr .= '<button type="submit" id="apply-pay-button" class="btn btn-primary pay-button">支付宝支付</button>';
    $retStr .= '</form>';
    $retStr .= "</td></tr></table></fieldset>";
    return $retStr;
}

/* 订单支付页面创建按钮 */
function alipay_make_html_order($order, $notify, $return) {

    $config = _get_payment_config ( 'alipay' );

    // 构造要请求的参数数组，无需改动
    $parameter = array (
        "service" => 'create_direct_pay_by_user',
        "partner" => $config ['account'] ['partner'],
        "seller_id" => $config ['account'] ['partner'],
        "payment_type" => '1',
        "notify_url" => $notify,
        "return_url" => $return,
        "out_trade_no" => 'order'.$order ['id'],
        "subject" => '支付订单 ：' . $order ['id'],
        "total_fee" => number_format ( $order ['amount']+$order ['freight'], 2,".","" ),
        "body" => '支付订单 ：' . $order ['id'],
        "_input_charset" => 'utf-8'
    );
    // 除去待签名参数数组中的空值和签名参数
    $para_filter = paraFilter ( $parameter );
    // 对待签名参数数组排序
    $para_sort = argSort ( $para_filter );
    $prestr = createLinkstring ( $para_sort );
    // 生成签名结果
    $mysign = md5 ( $prestr . $config ['account'] ['key'] );
    // 签名结果与签名方式加入请求提交参数组中
    $para_sort ['sign'] = $mysign;
    $para_sort ['sign_type'] = strtoupper ( 'MD5' );
    $retStr = "<fieldset> <legend><span style='color: red'>".$config['name']."</span></legend><table style=\"width: 100%\"><tr style=\"vertical-align: top\"><td style=\"padding-left: 20px;padding-right: 20px;\">";
    $retStr .= '<form target="make-payment" action="https://mapi.alipay.com/gateway.do" method="get">';
    foreach ( $para_sort as $key => $value ) {
        $retStr .= '<input type="hidden" name="' . $key . '" value="' . $value . '" />';
    }
    $retStr .= '<button type="submit" class="btn btn-sm btn-success pay-button">支付宝支付</button>';
    $retStr .= '</form>';
    $retStr .= "</td></tr></table></fieldset>";
    return $retStr;
}

/*支付宝支付回调*/
function alipay_callback() {
    $config = _get_payment_config ( 'alipay' );
    // $isSign = getSignVeryfy ( $_REQUEST, $_REQUEST ["sign"] );
    $id = trim ( $_REQUEST ['out_trade_no'] );
    $amount = $_REQUEST ['total_fee'];
    // 获取支付宝远程服务器ATN结果（验证是否是支付宝发来的消息）
    $responseTxt = 'false';
    if (! empty ( $_REQUEST ["notify_id"] )) {
        $responseTxt = getResponse ( $_REQUEST ["notify_id"] );
    }
    // 验证
    // $responsetTxt的结果不是true，与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
    // isSign的结果不是true，与安全校验码、请求时的参数格式（如：带自定义参数等）、编码格式有关
    if (preg_match ( "/true$/i", $responseTxt )) {
        $verify = true;
    } else {
        $verify = false;
    }

    if ($verify) {
        if ($_REQUEST ['trade_status'] == 'TRADE_FINISHED' || $_REQUEST ['trade_status'] == 'TRADE_SUCCESS') {
            $success = true;
        } else {
            $success = false;
        }
    }
    $ok = $verify && $success;
    $amount = floatval ( $amount );
    return array (
        $verify && $success,
        $id,
        $amount,
        $ok ? 'success' : 'fail'
    );
}

/*微信支付生成html*/
function ryfpaywx_make_html($recharge, $entry, $return)
{
    $config = _get_payment_config('ryfpaywx');
    $mer_id = $config ['account'] ['merId'];
    $userId = $recharge ['id'];
    $transSeqId = $recharge ['id'] . ":" . rand(1000,9999);
    $transAmt = number_format($recharge ['amount'], 2, ".", "" );
    $gateId = "ryfpaywx";
    $liqType = "T0";
    $retUrl = $return;
    $bgRetUrl = $entry;
    $paySrc = "PC";
    $chkValueRec = $mer_id . $userId . $transSeqId . $transAmt . $gateId . $liqType . $retUrl . $bgRetUrl . $config["account"]["key"];
    $chkValue = md5($chkValueRec);
    $retStr = "<fieldset> <legend><span style='color: red'>".$config['name']."</span></legend><table style=\"width: 100%\"><tr style=\"vertical-align: top\"><td style=\"padding-left: 20px;padding-right: 20px;\">";
    $retStr .= "<form method=\"post\" target=\"make-payment\"  action=\"http://114.215.180.135/mobile/ss/gatePayPage.do\" style=\" margin:10px auto\">\n\t<input type=\"hidden\" name=\"merId\" value =\"" . $mer_id . "\">\n\t<input type=\"hidden\" name=\"userId\" value=\"" . $userId . "\">\n\t<input type=\"hidden\" name=\"transSeqId\" value=\"" . $transSeqId . "\">\n\t<input type=\"hidden\" name=\"transAmt\" value=\"" . $transAmt . "\">\n\t<input type=\"hidden\" name=\"gateId\" value=\"" . $gateId . "\">\n\t<input type=\"hidden\" name=\"liqType\" value=\"" . $liqType . "\">\n\t<input type=\"hidden\" name=\"retUrl\" value=\"" . $retUrl . "\">\n\t<input type=\"hidden\" name=\"bgRetUrl\" value=\"" . $bgRetUrl . "\">\n\t<input type=\"hidden\" name=\"paySrc\" value=\"" . $paySrc . "\">\n\t<input type=\"hidden\" name=\"chkValue\" value=\"" . $chkValue . "\">\n\t<button type=\"submit\" class=\"btn btn-primary pay-button\">微信扫码支付</button>\n</form>";
    $retStr .= "</td></tr></table></fieldset>";
    return $retStr;
}

function ryfpaywx_make_html_order($order, $notify_ryfpaywx, $return_ryfpaywx)
{
    $config = _get_payment_config('ryfpaywx');
    $mer_id = $config ['account'] ['merId'];
    $userId = $order ['id'];
    $transSeqId =  'order'.$order ['id'] . ":" . rand(1000,9999);
    $transAmt =  number_format ( $order ['amount']+$order ['freight'], 2,".","" );
    $gateId = "ryfpaywx";
    $liqType = "T0";
    $retUrl = $return_ryfpaywx;
    $bgRetUrl = $notify_ryfpaywx;
    $paySrc = "PC";
    $chkValueRec = $mer_id . $userId . $transSeqId . $transAmt . $gateId . $liqType . $retUrl . $bgRetUrl . $config["account"]["key"];
    $chkValue = md5($chkValueRec);
    $retStr = "<fieldset> <legend><span style='color: red'>".$config['name']."</span></legend><table style=\"width: 100%\"><tr style=\"vertical-align: top\"><td style=\"padding-left: 20px;padding-right: 20px;\">";
    $retStr .= "<form method=\"post\" target=\"make-payment\"  action=\"http://114.215.180.135/mobile/ss/gatePayPage.do\">\n\t<input type=\"hidden\" name=\"merId\" value =\"" . $mer_id . "\">\n\t<input type=\"hidden\" name=\"userId\" value=\"" . $userId . "\">\n\t<input type=\"hidden\" name=\"transSeqId\" value=\"" . $transSeqId . "\">\n\t<input type=\"hidden\" name=\"transAmt\" value=\"" . $transAmt . "\">\n\t<input type=\"hidden\" name=\"gateId\" value=\"" . $gateId . "\">\n\t<input type=\"hidden\" name=\"liqType\" value=\"" . $liqType . "\">\n\t<input type=\"hidden\" name=\"retUrl\" value=\"" . $retUrl . "\">\n\t<input type=\"hidden\" name=\"bgRetUrl\" value=\"" . $bgRetUrl . "\">\n\t<input type=\"hidden\" name=\"paySrc\" value=\"" . $paySrc . "\">\n\t<input type=\"hidden\" name=\"chkValue\" value=\"" . $chkValue . "\">\n\t<button type=\"submit\" class=\"btn btn-primary pay-button\">".$config['name']."</button>\n</form>";
    $retStr .= "</td></tr></table></fieldset>";
    return $retStr;
}

/*微信支付回调*/
function ryfpaywx_callback()
{
    $config = _get_payment_config('ryfpaywx');

    $merId = trim($_REQUEST ['merId']);
    $transSeqId = $_REQUEST ['transSeqId'];
    $transAmt = $_REQUEST ['transAmt'];
    $transFee = $_REQUEST ['transFee'];
    $merPriv = $_REQUEST ['merPriv'];
    $gateId = $_REQUEST ['gateId'];
    $transStat = $_REQUEST ['transStat'];
    $chkValue = $_REQUEST ['chkValue'];

    $failCase = $_REQUEST ['failCase'];
    // 签名验证
    $chkValue_1 = md5($merId . $transSeqId . $transAmt . $transFee . $merPriv . $gateId . $transStat . $failCase . $config["account"]["key"]);

    // 验证
    if ($config ['account'] ['merId'] == $merId) {
        $verify = true;
    } else {
        $verify = false;
    }
    if ($verify) {
        if ($transStat == 'S') {
            $success = true;
        } else {
            $success = false;
        }
    }
    if (strtoupper($chkValue) == strtoupper($chkValue_1)) {
        $chkValueFlg = true;
    }else{
        $chkValueFlg = false;
    }

    $ok = $verify && $success&& $chkValueFlg;
    $amount = floatval($transAmt);
    logResult($verify . '--' . $success);

    $transSeqId_real = explode(":",$transSeqId);

    $transSeqId_real = $transSeqId_real[0];

    return array(
        $ok,
        $transSeqId_real,
        $amount,
        $ok ? 'RECV_' . $transSeqId : 'fail'
    );
}

/*掌中宝支付生成Html*/
function zzb_make_html($recharge, $entry, $return)
{
    $config = _get_payment_config('zzb');
    $mer_id = $config ['account'] ['merId'];
    $userId = $recharge ['id'];
    $transSeqId = $recharge ['id'] . ":" . rand(1000, 9999);
    $transAmt = number_format($recharge ['amount'], 2, ".", "" );
    $liqType = "T0";
    $retUrl = $return;
    $bgRetUrl = $entry;
    $paySrc = "PC";
    $paySrcH5 = "nor";
    $retStr = "";

    $retStr .= "<fieldset> <legend><span style='color: red'>掌中宝支付</span></legend><table style=\"width: 100%\"><tr style=\"vertical-align: top\">";
    foreach ($config['gate'] as $key => $value) {
        $gateId = $value["gateId"];
        $gateName = $value["gateName"];
        $chkValueRec = $mer_id . $userId . $transSeqId . $transAmt . $gateId . $liqType . $retUrl . $bgRetUrl . $config["account"]["key"];
        $chkValue = md5($chkValueRec);
        if ($gateId == "payeco" || $gateId == "eposgicp"  || $gateId == "reapalx" ) {
            $paySrc = $paySrcH5;
        }
        $retStr .= "<td class='tdStyle'><form method=\"post\" target=\"make-payment\"  action=\"http://114.215.180.135/mobile/ss/gatePayPage.do\" style=\"max-width:300px; margin:0 auto\">\n\t<input type=\"hidden\" name=\"merId\" value =\"" . $mer_id . "\">\n\t<input type=\"hidden\" name=\"userId\" value=\"" . $userId . "\">\n\t<input type=\"hidden\" name=\"transSeqId\" value=\"" . $transSeqId . "\">\n\t<input type=\"hidden\" name=\"transAmt\" value=\"" . $transAmt . "\">\n\t<input type=\"hidden\" name=\"gateId\" value=\"" . $gateId . "\">\n\t<input type=\"hidden\" name=\"liqType\" value=\"" . $liqType . "\">\n\t<input type=\"hidden\" name=\"retUrl\" value=\"" . $retUrl . "\">\n\t<input type=\"hidden\" name=\"bgRetUrl\" value=\"" . $bgRetUrl . "\">\n\t<input type=\"hidden\" name=\"paySrc\" value=\"" . $paySrc . "\">\n\t<input type=\"hidden\" name=\"chkValue\" value=\"" . $chkValue . "\">\n\t<button type=\"submit\" class=\"btn btn-primary pay-button\">$gateName</button>\n</form>";
        $paySrc = "PC";
        $retStr .= "</td>";
    }
    $retStr .= "</tr></table></fieldset>";
    return $retStr;
}
/*订单-掌中宝支付*/
function zzb_make_html_order($order, $entry, $return)
{
    $config = _get_payment_config('zzb');
    $mer_id = $config ['account'] ['merId'];
    $userId = $order ['id'];
    $transSeqId = $order ['id'] . ":" . rand(1000, 9999);
    $transAmt = number_format($order ['amount'], 2, ".", "" );
    $liqType = "T0";
    $retUrl = $return;
    $bgRetUrl = $entry;
    $paySrc = "PC";
    $paySrcH5 = "nor";
    $retStr = "";

    $retStr .= "<fieldset> <legend><span style='color: red'>掌中宝支付</span></legend><table style=\"width: 100%\"><tr style=\"vertical-align: top\">";
    foreach ($config['gate'] as $key => $value) {
        $gateId = $value["gateId"];
        $gateName = $value["gateName"];
        $chkValueRec = $mer_id . $userId . $transSeqId . $transAmt . $gateId . $liqType . $retUrl . $bgRetUrl . $config["account"]["key"];
        $chkValue = md5($chkValueRec);
        if ($gateId == "payeco" || $gateId == "eposgicp"  || $gateId == "reapalx" ) {
            $paySrc = $paySrcH5;
        }
        $retStr .= "<td style=\"padding-left: 20px;padding-right: 20px;\"><form method=\"post\" target=\"make-payment\"  action=\"http://114.215.180.135/mobile/ss/gatePayPage.do\" style=\"max-width:300px; margin:0 auto\">\n\t<input type=\"hidden\" name=\"merId\" value =\"" . $mer_id . "\">\n\t<input type=\"hidden\" name=\"userId\" value=\"" . $userId . "\">\n\t<input type=\"hidden\" name=\"transSeqId\" value=\"" . $transSeqId . "\">\n\t<input type=\"hidden\" name=\"transAmt\" value=\"" . $transAmt . "\">\n\t<input type=\"hidden\" name=\"gateId\" value=\"" . $gateId . "\">\n\t<input type=\"hidden\" name=\"liqType\" value=\"" . $liqType . "\">\n\t<input type=\"hidden\" name=\"retUrl\" value=\"" . $retUrl . "\">\n\t<input type=\"hidden\" name=\"bgRetUrl\" value=\"" . $bgRetUrl . "\">\n\t<input type=\"hidden\" name=\"paySrc\" value=\"" . $paySrc . "\">\n\t<input type=\"hidden\" name=\"chkValue\" value=\"" . $chkValue . "\">\n\t<button type=\"submit\" class=\"btn btn-primary pay-button\">$gateName</button>\n</form>";
        $paySrc = "PC";
        $retStr .= "</td>";
    }
    $retStr .= "</tr></table></fieldset>";
    return $retStr;
}

/*掌中宝支付回调*/
function zzb_callback()
{
    $config = _get_payment_config('zzb');
    $merId = trim($_REQUEST ['merId']);
    $transSeqId = $_REQUEST ['transSeqId'];
    $transAmt = $_REQUEST ['transAmt'];
    $transFee = $_REQUEST ['transFee'];
    $merPriv = $_REQUEST ['merPriv'];
    $gateId = $_REQUEST ['gateId'];
    $transStat = $_REQUEST ['transStat'];
    $chkValue = $_REQUEST ['chkValue'];
    $failCase = $_REQUEST ['failCase'];

    // 签名验证
    $chkValue_1 = md5($merId . $transSeqId . $transAmt . $transFee . $merPriv . $gateId . $transStat . $failCase . $config["account"]["key"]);

    //logResult($transSeqId . '--' . $json);

    // 验证
    if ($config ['account'] ['merId'] == $merId) {
        $verify = true;
    } else {
        $verify = false;
    }
    if ($verify) {
        if ($transStat == 'S') {
            $success = true;
        } else {
            $success = false;
        }
    }
    if (strtoupper($chkValue) == strtoupper($chkValue_1)) {
        $chkValueFlg = true;
    } else {
        $chkValueFlg = false;
    }

    $ok = $verify && $success && $chkValueFlg;
    $amount = floatval($transAmt);
    logResult($verify . '--' . $success);

    $transSeqId_real = explode(":", $transSeqId);

    $transSeqId_real = $transSeqId_real[0];

    return array(
        $ok,
        $transSeqId_real,
        $amount,
        $ok ? 'RECV_' . $transSeqId : 'fail'
    );
}
/*订单-掌中宝回调*/
function zzb_callback_order()
{
    $config = _get_payment_config('zzb');
    $merId = trim($_REQUEST ['merId']);
    $transSeqId = $_REQUEST ['transSeqId'];
    $transAmt = $_REQUEST ['transAmt'];
    $transFee = $_REQUEST ['transFee'];
    $merPriv = $_REQUEST ['merPriv'];
    $gateId = $_REQUEST ['gateId'];
    $transStat = $_REQUEST ['transStat'];
    $chkValue = $_REQUEST ['chkValue'];
    $failCase = $_REQUEST ['failCase'];

    // 签名验证
    $chkValue_1 = md5($merId . $transSeqId . $transAmt . $transFee . $merPriv . $gateId . $transStat . $failCase . $config["account"]["key"]);

    //logResult($transSeqId . '--' . $json);

    // 验证
    if ($config ['account'] ['merId'] == $merId) {
        $verify = true;
    } else {
        $verify = false;
    }
    if ($verify) {
        if ($transStat == 'S') {
            $success = true;
        } else {
            $success = false;
        }
    }
    if (strtoupper($chkValue) == strtoupper($chkValue_1)) {
        $chkValueFlg = true;
    } else {
        $chkValueFlg = false;
    }

    $ok = $verify && $success && $chkValueFlg;
    $amount = floatval($transAmt);
    logResult($verify . '--' . $success);

    $transSeqId_real = explode(":", $transSeqId);

    $transSeqId_real = $transSeqId_real[0];

    return array(
        $ok,
        $transSeqId_real,
        $amount,
        $ok ? 'RECV_' . $transSeqId : 'fail'
    );
}

/**
 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
 *
 * @param $para 需要拼接的数组
 *        	return 拼接完成以后的字符串
 */
function createLinkstring($para) {
    $arg = "";
    while ( list ( $key, $val ) = each ( $para ) ) {
        $arg .= $key . "=" . $val . "&";
    }
    // 去掉最后一个&字符
    $arg = substr ( $arg, 0, count ( $arg ) - 2 );

    // 如果存在转义字符，那么去掉转义
    if (get_magic_quotes_gpc ()) {
        $arg = stripslashes ( $arg );
    }

    return $arg;
}
/**
 * 对数组排序
 *
 * @param $para 排序前的数组
 *        	return 排序后的数组
 */
function argSort($para) {
    ksort ( $para );
    reset ( $para );
    return $para;
}

/**
 * 除去数组中的空值和签名参数
 *
 * @param $para 签名参数组
 *        	return 去掉空值与签名参数后的新签名参数组
 */
function paraFilter($para) {
    $para_filter = array ();
    while ( list ( $key, $val ) = each ( $para ) ) {
        if ($key == "sign" || $key == "sign_type" || $key == "_is_return_" || $val == "")
            continue;
        else
            $para_filter [$key] = $para [$key];
    }
    return $para_filter;
}
/**
 * 获取返回时的签名验证结果
 *
 * @param $para_temp 通知返回来的参数数组
 * @param $sign 返回的签名结果
 * @return 签名验证结果
 */
function getSignVeryfy($para_temp, $sign) {
    $config = _get_payment_config ( 'alipay' );
    // 除去待签名参数数组中的空值和签名参数
    $para_filter = paraFilter ( $para_temp );

    // 对待签名参数数组排序
    $para_sort = argSort ( $para_filter );

    // 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
    $prestr = createLinkstring ( $para_sort );
    $isSgin = false;
    $isSgin = md5Verify ( $prestr, $sign, $config ['account'] ['key'] );

    return $isSgin;
}
/**
 * 验证签名
 *
 * @param $prestr 需要签名的字符串
 * @param $sign 签名结果
 * @param $key 私钥
 *        	return 签名结果
 */
function md5Verify($prestr, $sign, $key) {
    $prestr = $prestr . $key;
    $mysgin = md5 ( $prestr );

    if ($mysgin == $sign) {
        return true;
    } else {
        return false;
    }
}
/**
 * 获取远程服务器ATN结果,验证返回URL
 *
 * @param $notify_id 通知校验ID
 * @return 服务器ATN结果 验证结果集：
 *         invalid命令参数不对 出现这个错误，请检测返回处理中partner和key是否为空
 *         true 返回正确信息
 *         false 请检查防火墙或者是服务器阻止端口问题以及验证时间是否超过一分钟
 */
function getResponse($notify_id) {
    $config = _get_payment_config ( 'alipay' );
    $partner = trim ( $config ['account'] ['partner'] );
    $veryfy_url = 'http://notify.alipay.com/trade/notify_query.do?';
    $veryfy_url = $veryfy_url . "partner=" . $partner . "&notify_id=" . $notify_id;
    $public_key = Z_DR . '/' . $config ['account'] ['public_key'];
    $responseTxt = getHttpResponseGET ( $veryfy_url, $public_key );

    return $responseTxt;
}
/**
 * 远程获取数据，GET模式
 * 注意：
 * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
 * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\\cacert.pem'
 *
 * @param $url 指定URL完整路径地址
 * @param $cacert_url 指定当前工作目录绝对路径
 *        	return 远程输出的数据
 */
function getHttpResponseGET($url, $cacert_url) {
    $curl = curl_init ( $url );
    curl_setopt ( $curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
    curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 ); // 显示输出结果
    curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, true ); // SSL证书认证
    curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, 2 ); // 严格认证
    curl_setopt ( $curl, CURLOPT_CAINFO, $cacert_url ); // 证书地址
    $responseText = curl_exec ( $curl );
    curl_close ( $curl );
    return $responseText;
}
/**
 * 写日志，方便测试（看网站需求，也可以改成把记录存入数据库）
 * 注意：服务器需要开通fopen配置
 *
 * @param $word 要写入日志里的文本内容
 *        	默认值：空值
 */
function logResult($word = '') {
    $fp = fopen ( "log.txt", "a" );
    flock ( $fp, LOCK_EX );
    fwrite ( $fp, "执行日期：" . strftime ( "%Y%m%d%H%M%S", time () ) . "\n" . $word . "\n" );
    flock ( $fp, LOCK_UN );
    fclose ( $fp );
}


function alipay_callback_order() {
    $config = _get_payment_config ( 'alipay' );
    /*	//$isSign = getSignVeryfy ( $_REQUEST, $_REQUEST ["sign"] );
        //$id = explode(':',$_REQUEST ['out_trade_no'] )[0];*/

    $id = substr($_REQUEST ['out_trade_no'],5);

    $amount = $_REQUEST ['total_fee'];

    // 获取支付宝远程服务器ATN结果（验证是否是支付宝发来的消息）
    $responseTxt = 'false';
    if (! empty ( $_REQUEST ["notify_id"] )) {
        $responseTxt = getResponse ( $_REQUEST ["notify_id"] );
    }
    // 验证
    // $responsetTxt的结果不是true，与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
    // isSign的结果不是true，与安全校验码、请求时的参数格式（如：带自定义参数等）、编码格式有关
    if (preg_match ( "/true$/i", $responseTxt )) {
        $verify = true;
    } else {
        $verify = false;
    }
    if ($verify) {
        if ($_REQUEST ['trade_status'] == 'TRADE_FINISHED' || $_REQUEST ['trade_status'] == 'TRADE_SUCCESS') {
            $success = true;
        } else {
            $success = false;
        }
    }
    $ok = $verify && $success;
    $amount = floatval ( $amount );
    return array (
        $verify && $success,
        $id,
        $amount,
        $ok ? 'success' : 'fail'
    );
}

function ryfpaywx_callback_order() {
    $config = _get_payment_config('ryfpaywx');

    $merId = trim($_REQUEST ['merId']);
    $transSeqId = $_REQUEST ['transSeqId'];
    $transAmt = $_REQUEST ['transAmt'];
    $transFee = $_REQUEST ['transFee'];
    $merPriv = $_REQUEST ['merPriv'];
    $gateId = $_REQUEST ['gateId'];
    $transStat = $_REQUEST ['transStat'];
    $chkValue = $_REQUEST ['chkValue'];

    $failCase = $_REQUEST ['failCase'];

    // 签名验证
    $chkValue_1 = md5($merId . $transSeqId . $transAmt . $transFee . $merPriv . $gateId . $transStat . $failCase . $config["account"]["key"]);

    //logResult($transSeqId . '--' . $json);

    // 验证
    if ($config ['account'] ['merId'] == $merId) {
        $verify = true;
    } else {
        $verify = false;
    }
    if ($verify) {
        if ($transStat == 'S') {
            $success = true;
        } else {
            $success = false;
        }
    }
    if (strtoupper($chkValue) == strtoupper($chkValue_1)) {
        $chkValueFlg = true;
    }else{
        $chkValueFlg = false;
    }

    $ok = $verify && $success&& $chkValueFlg;
    $amount = floatval($transAmt);
    logResult($verify . '--' . $ok);

    $transSeqId_real = explode(":",$transSeqId);

    $transSeqId_real = $transSeqId_real[0];
    $transSeqId_real = substr($transSeqId_real,5);
    return array(
        $ok,
        $transSeqId_real,
        $amount,
        $ok ? 'RECV_' . $transSeqId : 'fail'
    );
}

function order_callback_by_type($method) {
    switch ($method) {
        case 'alipay':
            return alipay_callback_order();
        case 'ryfpaywx':
            return ryfpaywx_callback_order();
        case 'zzb' :
            return zzb_callback_order();
    }
    throw new Exception ( '错误的方式: ' . $method . ', ' . $_GET ['method_code'] );
}